import React from 'react'
import {connect} from 'react-redux'
import { messages, queryCurrencyPrecision } from "share/common";
import AdvancedTable from 'components/advanced-table'
import { Button, Alert, message, Spin } from 'antd'
import queryService from 'containers/pay/bank-query/query.service'
import 'styles/pay/pay-workbench/pay-workbench.scss'
import Template from "components/UI/template"

const { Middle } = Template;

class bankQuery extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      searchForm: [
        {
          id: 'searchCompanyId', label: messages('finance-4.key20')/*公司*/, component: 'Chooser',
          props: {
            type: 'available_company_setOfBooks',
            placeholder: messages('finance-4.key47')/*请输入公司名称*/,
            listExtraParams: { userOID: props.loginUser.userOID, enabled: true },
            valueKey: 'id',
            labelKey: 'name',
            single: true
          },
          parser: value => ({
            searchCompanyId: value ? value.map(item => item.id) : null
          })
        },
        {
          id: 'accountNumber', label: messages('finance-4.key21')/*银行账户*/, component: 'Input',
          props: { placeholder: messages('common.please.input')/*请输入*/ + messages('finance-4.key48')/*银行账户名称/账号*/ }
        }
      ],
      columns: [
        {
          title: messages('finance-4.key49')/*银行账户名称*/, dataIndex: 'bankAccountName',
          render: (value, record) => record.companyBank.bankAccountName
        },
        {
          title: messages('finance-4.key50')/*银行账户账号*/, dataIndex: 'bankAccountNumber',
          render: (value, record) => record.companyBank.bankAccountNumber
        },
        {
          title: messages('finance-4.key22')/*银行名称*/, dataIndex: 'bankName',
          render: (value, record) => record.companyBank.bankName
        },
        {
          title: messages('finance-4.key51')/*银行详细地址*/, dataIndex: 'bankAddress',
          render: (value, record) => record.companyBank.bankAddress
        },
        {
          title: messages('finance-4.key52')/*公司名称*/, dataIndex: 'bankAccountCompanyName'
        },
        {
          title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode',
          render: (value, record) => record.companyBank.currencyCode
        },
        {
          title: messages('finance-4.key53')/*账户余额*/, dataIndex: 'surplus',
          render: (value, record) => value ? this.filterMoney(value,queryCurrencyPrecision(record.companyBank.currencyCode)) : '-'
        },
        {
          title: messages('common.operation')/*操作*/, dataIndex: 'operator',
          render: (value, record) => <a onClick={() => this.handleQuery(record)}>{messages('finance-4.key54')/*查询余额*/}</a>
        }
      ],
      rowSelection: {
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      selectedData: [],
      loading: false
    };
  }

  onSelectChange = selectedRowKeys => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  onSelectItem = (record, selected) => {
    const { selectedData } = this.state;
    if (selected) {
      selectedData.push(record);
    } else {
      selectedData.splice(selectedData.findIndex(item => item.id === record.id),1);
    }
    this.setState({ selectedData });
  };

  onSelectAll = (selected, selectedRows, changeRows) => {
    changeRows.map(changeRow => this.onSelectItem(changeRow, selected))
  };

  handleQuery = (record, batch) => {
    let params = [];
    let { selectedData, rowSelection } = this.state;
    if (batch) {
      if (selectedData.length > 10) {
        message.error(messages('finance-4.key55')/*批量查询银行账户数量不得超过10个*/)
      }
      selectedData.map(item => {
        params.push(this.handleData(item))
      });
    } else {
      params.push(this.handleData(record))
    }
    this.setState({ loading: true });
    queryService.queryAccountBalance(params).then(res => {
      const { dataSource } = this.advancedTableRef.state, { data } = res;
      dataSource.map(item => item.surplus = this.getAccountBalance(item, data));
      params.forEach(item => {
        selectedData = selectedData.filter(record => record.id !== item.id);
        rowSelection.selectedRowKeys = rowSelection.selectedRowKeys.filter(record => record !== item.id);
      });
      this.setState({ selectedData, rowSelection, loading: false }, () => {
        this.advancedTableRef.setState({ dataSource }, () => {
          this.advancedTableRef.resetTableScroll();
        })
      });
    }).catch(e => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    })
  };

  getAccountBalance = (item, arr) => {
    let res = arr.find(record => record.id === item.id);
    return (res && typeof res.accountBalance === 'number') ? res.accountBalance : item.surplus
  };

  handleData = item => {
    return {
      id: item.id,
      acctNo: item.companyBank.bankAccountNumber,
      acctName: item.companyBank.bankAccountName,
      channel: item.bankPayInfo.vendor
    }
  };

  service = (page, pageSize, searchParams) => {
    const { loginUser } = this.props;
    return queryService.getBankList(loginUser.userOID, Object.assign(searchParams, { isBankPay: true }))
  };

  render(){
    const { columns, searchForm, rowSelection, loading } = this.state;
    return (
      <Template className={'normal-scss'}>
        <Middle>
          <Spin spinning={loading}>
            <AdvancedTable
              title={messages('finance-4.key56')/*银行账户余额查询*/}
              service={this.service}
              rowKey="id"
              onRef={ref => this.advancedTableRef = ref}
              tableName={'bank-query'}
              rowSelection={ rowSelection }
              searchForm={searchForm}
              columns={columns}
            >
              <div className="table-header">
                <div className="table-header-buttons">
                  <Button onClick={() => this.handleQuery({}, true)} type='primary'>{messages('finance-4.key57')/*余额查询*/}</Button>
                  <Alert
                    type="info"
                    showIcon
                    message={messages('finance-4.key58')/*仅银企直联生效中的银行账户支持查询余额，批量查询银行账户数量不得超过10个*/}
                    style={{display: 'inline-block'}}
                  />
                </div>
              </div>
            </AdvancedTable>
          </Spin>
        </Middle>
      </Template>
    )
  }
}

function mapStateToProps(state)  {
  return {
    loginUser: state.login.loginUser
  }
}

export default connect(mapStateToProps)(bankQuery);
